<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\BaseController;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Cookie;
use think\facade\Session;

class Index extends Base
{

    public function index()     //登录方法
    {
        if($this->request->isPost()){      //获取登录信息
            $data = $this->request->post();

            if(!captcha_check($data['captcha'])){      //验证验证码
                return json([
                    'code'=>400,
                    'msg'=>'验证码错误'
                ]);

            };

            $user = Db::table('admin')
                ->where([
                    'admin_name'=>$data['admin_name'],
                    'status'=>'0'
                    ])
                ->field('id,admin_name,admin_pwd,status')
                ->find();

            if(!$user){
                return json([
                    'code'=>400,
                    'msg'=>'用户名不存在'
                ]);
            }

            if($user['admin_pwd']!=md5($data['admin_pwd'])){
                return json([
                    'code'=>400,
                    'msg'=>'密码输入错误'
                ]);
            }



            $cookie = $this->makeUserCookie($user['admin_name'],$user['admin_pwd']);
            Session::set($cookie,$user); //设置 用户Session
            cookie('user', $cookie);

            return json([
                'code'=>200,
                'msg'=>'登录成功'
            ]);

        }

        return view('');
    }

    private function makeUserCookie($admin_name,$admin_pwd)  //私有的创建cookie方法 入参为用户数据
    {
        $rand = (string)rand(100000,999999);  //两边的随机数
        $str = base64_encode(md5($rand));
        $user_code = sha1(md5(base64_encode(md5($admin_name.$admin_pwd))));
        $code = md5($str.$user_code.$str);
        $user['rand'] = $rand;

        return $code;
    }
}
